<?php
namespace app\controllers\tag;

use fate\http\Request;
use app\models\Posts;
use app\models\User;
use app\libs\Page;
use app\libs\Util;
use app\libs\LibUser;

class IndexController extends \fate\web\Controller {
    public function run() {
        $req = Request::getInstance();
        $k = Util::plainText($req->getQueryString('k'));
        $p = $req->getQueryString('p');

        if(!is_numeric($p)) {
            $p = 1;
        }

        // data
        $post = new Posts();
        $pageSize = 20;
        $where = "status = 1 and instr(tags, '{$k}')";
        $total = $post->count($where);

        $pageString = (new Page($total, $pageSize))->show();
        $data = $post->getListByPage(
            'id,uid,tags,title,thumb,brief,views,post_time,status',
            $where, $p, $pageSize);

        // user info
        if($data) {
            $user = new User();
            for($i=0,$len=count($data); $i<$len; $i++) {
                $data[$i]['str_uid'] = LibUser::encodeId($data[$i]['uid']);
                $data[$i]['user_info'] = $user->getOne('gender,user_name,avatar', $data[$i]['uid']);
            }
        }

        $this->getView()->enableLayout = true;
        $this->render('@themes/tag/index', [
            'nav' => $k,
            'list' => $data,
            'p' => $p,
            'pageSize' => $pageSize,
            'total' => $total,
            'pageString' => $pageString,
        ]);
    }
}
